﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Reflection;
using System.Xml;
using System.IO;

namespace ProtocolBuilder
{
    static class FieldTypeManager
    {
        private static Dictionary<string, FieldType> fieldTempleteDict;

        static FieldTypeManager()
        {
            XmlReader reader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("ProtocolBuilder.protocol_type_map.xml"));
            fieldTempleteDict = LoadConfigFile(reader);
        }

        public static FieldType GetTemplete(string type)
        {
            return fieldTempleteDict.ContainsKey(type) ? fieldTempleteDict[type] : null;
        }

        public static IEnumerable<string> FieldTypes
        {
            get
            {
                return fieldTempleteDict.Keys;
            }
        }

        private static Dictionary<string, FieldType> LoadConfigFile(XmlReader reader)
        {
            Dictionary<string, FieldType> result = new Dictionary<string, FieldType>();
            XDocument document = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
            foreach (var field in document.Root.Element("fieldtypes").Elements("field"))
            {
                FieldType templete = new FieldType()
                {
                    AliasName = field.Attribute("alias").Value,
                    AssemblyName = field.Attribute("assembly").Value,
                    TypeFullName = field.Attribute("type").Value,
                };

                result.Add(templete.AliasName, templete);
            }

            return result;
        }

        private static Dictionary<string, FieldType> LoadConfigFile(string filename)
        {
            return LoadConfigFile(XmlReader.Create((filename)));
        }
    }
}
